<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\shop_admin\service;

use app\madmin\model\Merchant;
use app\shop_admin\model\Admin;
use app\shop_admin\model\Rule;
use app\shop_admin\model\RuleExtend;
use app\utils\TrimData;
use think\db\exception\PDOException;
use think\db\Query;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use think\facade\Env;
use think\facade\Request;
use think\model\Relation;

class OperationService
{

    /**
     * 校验登录信息
     * @param string $ip
     * @param string $username
     * @param string $password
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    private function check(string $ip, string $username, string $password)
    {

        $admin = Admin::withoutGlobalScope(['mallId', 'merchantId'])->where('status', 1)->getByUsername($username);
        if (!$admin || hash('sha256', $password) !== $admin->password) {
            return [HTTP_NOTACCEPT, '账号或密码错误'];
        }

        global $user;
        $user = $admin;

//        $typeIndate = Db::table('jiecheng_lessee')
//            ->where(['status' =>1])
//            ->whereNull("delete_time")
//            ->field('type,indate,site')
//            ->find($user->mall_id);
//        if (!$typeIndate){
//            return [HTTP_NOTACCEPT, '商城已禁用'];
//        }
//        if ($typeIndate['type'] === 0 && (empty($typeIndate['indate']) || strtotime($typeIndate['indate']) < time())){
//            return [HTTP_NOTACCEPT, '商城已过期，请联系管理员续费'];
//        }

        $merchant = Merchant::field('status,audit_type,name')->find($admin->merchant_id);
        if ($merchant->getData("status") != 1) {
            return [HTTP_NOTACCEPT, '商户已封禁,请联系管理员'];
        }

        unset($admin->password);
        $admin->login_ip = $ip;
        global $token;

        $token = "shop_" . createToken();
        $admin->ac_token = $token;
        $admin->save();

        $rule = $admin->role->rule()->where('rule.status', 1)->select();
        $ruleIds = array_column($rule->toArray(), 'id');
        $ruleList = Rule::with([
            'ruleExtend' => function (Relation $query) {
                return $query->visible(['rule_route', 'method']);
            }
        ])->where(['id' => $ruleIds])
            ->visible(['resource', 'level'])
            ->select();

        //归属
        $admin->affiliation = "shop";
        $admin->is_self = 0;
        $admin->audit_type = $merchant->audit_type;
        $admin->flag = false;

        Cache::store('redis')->set("shop_token:" . $admin->ac_token, $admin, 60 * 60 * 24 * 30);

        $msg = [
            "user" => $admin,
            "site" => $merchant->name,
        ];

        return [HTTP_SUCCESS,
            [
                'msg' => $msg,
                'token' => $admin->ac_token,
                'ruleList' => $ruleList
            ]
        ];
    }

    /**
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {
        $admin = Admin::field('id,username,avatar,name,mobile,role_id,is_root,status,create_time,update_time')->with('role');
        $admin = TrimData::searchDataTrim($admin, $data, ['name', 'mobile', 'begin_date', 'end_date']);

        $list = $admin->where($data)->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * @param array $data
     * @return array
     */
    public function save(array $data)
    {

        //校验username是否重复
        unset($data['is_root']);

        $data['login_ip'] = getIp();
        $admin = '';
        try {
            $admin = Admin::create($data);
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), "Index_username") !== false) {
                throw new \PDOException('账号已存在', HTTP_INVALID);
            }

            if (strpos($e->getMessage(), "Index_mobile") !== false) {
                throw new \PDOException('手机号已存在', HTTP_INVALID);
            }
        }
        return [HTTP_CREATED, $admin];
    }

    public function read(int $id)
    {
        $model = Admin::find($id);
        if ($model) {
            unset($model->password);
            unset($model->ac_token);
        }
        return [HTTP_SUCCESS, $model];
    }

    private function getAdmin($id)
    {
        $admin = admin::find($id);
        if (1 === $admin->is_root){
            throw new Exception("初始账号不能操作",HTTP_NOTACCEPT);
        }
    }


    public function update(int $id, array $data)
    {
        $this->getAdmin($id);
        $update_time = $data['update_time'];
        unset($data['update_time'],$data['is_root']);
        $admin = Admin::where('update_time', $update_time)
            ->where(['id' => $id,"is_root" => 0])
            ->save($data);
        return [HTTP_CREATED, $admin];
    }

    public function delete($id)
    {
        $this->getAdmin($id);
        Admin::destroy(function ($query) use ($id) {
            $query->where(['id' => $id,'is_root' =>0]);
        });
        return HTTP_NOCONTEND;
    }


    public function scopeSearch(Query $query, array $data)
    {
        $data = array_filter($data, function ($val) {
            return is_array($val) || (is_string($val) && "" != trim($val));
        });
        $query->alias("a")
            ->join("order_info b", "a.order_info_id = b.id", 'left')
            ->join("think_member c", "a.user_id = c.id")
            ->field("a.*,b.name,b.tel,c.username");
        foreach ($data as $k => $v) {
            if ($k === 'create_time' || $k === 'update_time') {
                if (!empty($v['begin']) && !empty($v['end'])) {
                    $query->whereTime("a." . $k, "between", [$v['begin'], $v['end']]);
                } elseif (!empty($v['begin'])) {
                    $query->whereTime("a." . $k, ">=", $v['begin']);
                } elseif (!empty($v['end'])) {
                    $query->whereTime("a." . $k, "<=", $v['end']);
                }
            } elseif ($k === 'username')
                $query->where("c." . $k, 'like', "%$v%");
            elseif ($k === "name")
                $query->where("b." . $k, 'like', "%$v%");
            elseif ($k === "order_num")
                $query->where("a." . $k, 'like', "%$v%");
            elseif ($k === "tel")
                $query->where("b." . $k, $v);
            else
                $query->where("a." . $k, $v);
        }
        return $query;

    }


    /**修改自身数据
     * @param int $id
     * @param array $data
     * @return array
     * @throws Exception
     */
    public function selfUp(int $id, array $data)
    {
        global $user;
        $where[] = ['id', '=', $id];
        if (isset($data['old_password'])) $where[] = ['password', '=', hash('sha256', $data['old_password'])];
        $admin = Admin::where($where)->find();
        if (isset($data['password']) && !isset($data['old_password'])) throw new Exception('修改密码必须提交原密码!', HTTP_INVALID);
        if (!isset($data['password']) && isset($data['old_password'])) throw new Exception('未提交新密码!', HTTP_INVALID);
        if (empty($admin)) throw new Exception('旧密码输入有误!', HTTP_INVALID);
        if ($id != $user->id) throw new Exception('无权修改他人数据!', HTTP_INVALID);
        if (isset($data['password'])) {
            $password = $data['password'];
            unset($data['old_password'], $data['password']);
            $data['password'] = hash('sha256', $password);
        }
        Admin::update($data, ['id' => $id], ['password', 'username', 'head', "mobile"]);
        return [HTTP_CREATED, "成功!"];
    }
}
